from datetime import datetime
from app import db

class User(db.Model):
    """用户模型"""
    __tablename__ = 'user'

    UserId = db.Column(db.Integer, autoincrement=True, primary_key=True)
    UserName = db.Column(db.String(50), nullable=False, unique=True)
    UserPassword = db.Column(db.String(200), nullable=False)
    UserEmail = db.Column(db.String(50), nullable=False, unique=True)
    UserNickname = db.Column(db.String(50), nullable=True, comment='用户昵称')
    UserAvatar = db.Column(db.String(200), nullable=True, comment='用户头像URL')
    UserBio = db.Column(db.String(200), nullable=True, comment='个人简介')
    UserGender = db.Column(db.String(10), nullable=True, comment='性别')
    UserBirthday = db.Column(db.Date, nullable=True, comment='生日')
    UserLocation = db.Column(db.String(100), nullable=True, comment='所在地')
    UserBalance = db.Column(db.Float, nullable=False, default=0.0)  # 用户余额，默认为0
    UserPoints = db.Column(db.Integer, nullable=False, default=0)   # 用户积分，默认为0
    LastLoginTime = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 添加评论关系
    comments = db.relationship('Comment', backref='user', lazy='dynamic')
    # 添加用户信息关系
    profile = db.relationship('UserProfile', backref='user', uselist=False, lazy='joined')

    def __repr__(self):
        return f'<User {self.UserName}>'
    
    def save(self):
        """保存到数据库"""
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except Exception as e:
            db.session.rollback()
            raise e
            
    def to_dict(self):
        """转换为字典"""
        data = {
            'id': self.UserId,
            'username': self.UserName,
            'email': self.UserEmail,
            'balance': float(self.UserBalance or 0),
            'points': int(self.UserPoints or 0)
        }
        # 添加用户信息
        if self.profile:
            data.update({
                'nickname': self.profile.Nickname,
                'avatar': self.profile.Avatar,
                'bio': self.profile.Bio,
                'gender': self.profile.Gender,
                'school': self.profile.School,
                'department': self.profile.Department,
                'last_login_time': self.profile.LastLoginTime.strftime('%Y-%m-%d %H:%M:%S') if self.profile.LastLoginTime else None,
                'create_time': self.profile.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.profile.CreateTime else None
            })
        return data

class UserProfile(db.Model):
    """用户信息模型"""
    __tablename__ = 'userprofile'

    ProfileId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), unique=True, nullable=False)
    Nickname = db.Column(db.String(50), nullable=True, comment='用户昵称')
    Avatar = db.Column(db.String(200), nullable=True, comment='用户头像URL')
    Bio = db.Column(db.String(200), nullable=True, comment='个人简介')
    Gender = db.Column(db.String(10), nullable=True, comment='性别')
    School = db.Column(db.String(100), nullable=True, comment='学校')
    Department = db.Column(db.String(100), nullable=True, comment='院系')
    LastLoginTime = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def __repr__(self):
        return f'<UserProfile {self.UserId}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'user_id': self.UserId,
            'nickname': self.Nickname,
            'avatar': self.Avatar,
            'bio': self.Bio,
            'gender': self.Gender,
            'school': self.School,
            'department': self.Department,
            'last_login_time': self.LastLoginTime.strftime('%Y-%m-%d %H:%M:%S') if self.LastLoginTime else None,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class Food(db.Model):
    """食品模型"""
    __tablename__ = 'food'

    FoodId = db.Column(db.Integer, autoincrement=True, primary_key=True)
    FoodName = db.Column(db.String(50), nullable=False)
    FoodPrice = db.Column(db.Float, nullable=False)
    FoodDetail = db.Column(db.String(200))
    FoodImage = db.Column(db.String(200))
    FoodType = db.Column(db.String(50), nullable=False)
    
    def __repr__(self):
        return f'<Food {self.FoodName}>'
    
    def save(self):
        """保存到数据库"""
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except Exception as e:
            db.session.rollback()
            raise e

class PointsRecord(db.Model):
    """积分记录模型"""
    __tablename__ = 'pointsrecord'

    RecordId = db.Column(db.Integer, autoincrement=True, primary_key=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Points = db.Column(db.Integer, nullable=False)  # 积分变动数量（正数为增加，负数为减少）
    Description = db.Column(db.String(200), nullable=False)  # 积分变动说明
    CreateTime = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    # 建立与用户表的关系
    user = db.relationship('User', backref=db.backref('points_records', lazy=True))

    def __repr__(self):
        return f'<PointsRecord {self.Points}>'
    
    def save(self):
        """保存到数据库"""
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except Exception as e:
            db.session.rollback()
            raise e

class BalanceRecord(db.Model):
    """余额记录模型"""
    __tablename__ = 'balancerecord'

    RecordId = db.Column(db.Integer, autoincrement=True, primary_key=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Amount = db.Column(db.Float, nullable=False)  # 余额变动金额（正数为增加，负数为减少）
    Description = db.Column(db.String(200), nullable=False)  # 余额变动说明
    CreateTime = db.Column(db.DateTime, nullable=False, default=datetime.now)

    # 建立与用户表的关系
    user = db.relationship('User', backref=db.backref('balance_records', lazy=True))

    def __repr__(self):
        return f'<BalanceRecord {self.RecordId}>'

    def save(self):
        """保存到数据库"""
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except Exception as e:
            db.session.rollback()
            raise e
            
    def to_dict(self):
        """转换为字典"""
        return {
            'record_id': self.RecordId,
            'user_id': self.UserId,
            'amount': float(self.Amount),
            'description': self.Description,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S')
        }

class Comment(db.Model):
    """评论模型"""
    __tablename__ = 'comment'

    CommentId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Content = db.Column(db.Text, nullable=False, comment='评论内容')
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    NewsId = db.Column(db.Integer, db.ForeignKey('news.NewsId'), nullable=False)
    ParentId = db.Column(db.Integer, db.ForeignKey('comment.CommentId'), nullable=True)
    LikeCount = db.Column(db.Integer, default=0, comment='点赞数')
    IsDeleted = db.Column(db.Boolean, default=False, comment='是否删除')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 添加自引用关系，用于回复功能
    replies = db.relationship('Comment', 
                            backref=db.backref('parent', remote_side=[CommentId]),
                            lazy='dynamic')

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.CommentId,
            'content': self.Content,
            'user_id': self.UserId,
            'user_name': self.user.UserName,
            'news_id': self.NewsId,
            'parent_id': self.ParentId,
            'like_count': self.LikeCount if self.LikeCount is not None else 0,
            'is_deleted': self.IsDeleted,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None,
            'replies': [reply.to_dict() for reply in self.replies.filter_by(IsDeleted=False)] if not self.ParentId else []
        }

class News(db.Model):
    """新闻模型"""
    __tablename__ = 'news'
    
    NewsId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Title = db.Column(db.String(200), nullable=False, comment='新闻标题')
    Content = db.Column(db.Text, nullable=False, comment='新闻内容')
    Summary = db.Column(db.String(500), nullable=True, comment='新闻摘要')
    Author = db.Column(db.String(50), nullable=False, comment='作者')
    Category = db.Column(db.String(50), nullable=False, comment='新闻分类')
    Tags = db.Column(db.String(200), nullable=True, comment='标签，逗号分隔')
    CoverImage = db.Column(db.String(200), nullable=True, comment='封面图片URL')
    CoverVideo = db.Column(db.String(200), nullable=True, comment='封面视频URL')
    CoverRadio = db.Column(db.String(200), nullable=True, comment='封面音频URL')
    ViewCount = db.Column(db.Integer, default=0, comment='浏览次数')
    LikeCount = db.Column(db.Integer, default=0, comment='点赞数')
    CommentCount = db.Column(db.Integer, default=0, comment='评论数')
    IsTop = db.Column(db.Boolean, default=False, comment='是否置顶')
    IsPublished = db.Column(db.Boolean, default=True, comment='是否发布')
    IsHot = db.Column(db.Boolean, default=False, comment='是否热门')
    PublishTime = db.Column(db.DateTime, nullable=True, comment='发布时间')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 添加评论关系
    comments = db.relationship('Comment', backref='news', lazy='dynamic')

    def to_dict(self):
        return {
            'id': self.NewsId,
            'title': self.Title,
            'content': self.Content,
            'summary': self.Summary,
            'author': self.Author,
            'category': self.Category,
            'tags': self.Tags.split(',') if self.Tags else [],
            'cover_image': self.CoverImage,
            'cover_video': self.CoverVideo,
            'cover_radio': self.CoverRadio,
            'view_count': self.ViewCount if self.ViewCount is not None else 0,
            'like_count': self.LikeCount if self.LikeCount is not None else 0,
            'comment_count': self.CommentCount if self.CommentCount is not None else 0,
            'is_top': self.IsTop,
            'is_published': self.IsPublished,
            'is_hot': self.IsHot,
            'publish_time': self.PublishTime.strftime('%Y-%m-%d %H:%M:%S') if self.PublishTime else None,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

    def to_simple_dict(self):
        """返回简化的新闻信息，用于列表展示"""
        return {
            'id': self.NewsId,
            'title': self.Title,
            'summary': self.Summary,
            'author': self.Author,
            'category': self.Category,
            'cover_image': self.CoverImage,
            'cover_video': self.CoverVideo,
            'cover_radio': self.CoverRadio,
            'view_count': self.ViewCount if self.ViewCount is not None else 0,
            'like_count': self.LikeCount if self.LikeCount is not None else 0,
            'comment_count': self.CommentCount if self.CommentCount is not None else 0,
            'is_top': self.IsTop,
            'is_hot': self.IsHot,
            'publish_time': self.PublishTime.strftime('%Y-%m-%d %H:%M:%S') if self.PublishTime else None
        }

class Book(db.Model):
    """书籍模型"""
    __tablename__ = 'book'

    BookId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Title = db.Column(db.String(200), nullable=False, comment='书籍标题')
    Author = db.Column(db.String(100), nullable=True, comment='作者')
    Type = db.Column(db.String(50), nullable=True, comment='类型')
    Price = db.Column(db.Float, nullable=True, comment='价格')
    Content = db.Column(db.Text, nullable=True, comment='内容简介')
    CoverImage = db.Column(db.String(200), nullable=True, comment='封面图片URL')
    ReviewCount = db.Column(db.Integer, nullable=False, default=0, comment='评论数')

    # 添加评价关系
    reviews = db.relationship('BookReview', backref='book', lazy='dynamic')

    def __repr__(self):
        return f'<Book {self.Title}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.BookId,
            'title': self.Title,
            'author': self.Author,
            'type': self.Type,
            'price': float(self.Price) if self.Price is not None else None,
            'content': self.Content,
            'cover_image': self.CoverImage,
            'review_count': self.ReviewCount if self.ReviewCount is not None else 0
        }

class BookReview(db.Model):
    """书籍评价模型"""
    __tablename__ = 'bookreview'

    ReviewId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    BookId = db.Column(db.Integer, db.ForeignKey('book.BookId'), nullable=False)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Content = db.Column(db.Text, nullable=False, comment='评价内容')
    LikeCount = db.Column(db.Integer, default=0, comment='点赞数')
    IsDeleted = db.Column(db.Boolean, default=False, comment='是否删除')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 建立与用户的关系
    user = db.relationship('User', backref=db.backref('book_reviews', lazy='dynamic'))

    def __repr__(self):
        return f'<BookReview {self.ReviewId}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.ReviewId,
            'book_id': self.BookId,
            'user_id': self.UserId,
            'user_name': self.user.UserName,
            'content': self.Content,
            'like_count': self.LikeCount if self.LikeCount is not None else 0,
            'is_deleted': self.IsDeleted,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class Bonus(db.Model):
    """奖励模型"""
    __tablename__ = 'bonus'

    BonusId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Title = db.Column(db.String(100), nullable=False, comment='奖励标题')
    Image = db.Column(db.String(200), nullable=True, comment='奖励图片URL')
    Points = db.Column(db.Integer, nullable=False, comment='所需积分')
    Description = db.Column(db.Text, nullable=True, comment='奖励描述')
    IsActive = db.Column(db.Boolean, default=True, comment='是否激活')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    def __repr__(self):
        return f'<Bonus {self.Title}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.BonusId,
            'title': self.Title,
            'image': self.Image,
            'points': self.Points,
            'description': self.Description,
            'is_active': self.IsActive,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class Order(db.Model):
    """订单模型"""
    __tablename__ = 'order'

    OrderId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Type = db.Column(db.String(20), nullable=False, comment='订单类型(book/food)')
    ItemId = db.Column(db.Integer, nullable=False, comment='商品ID')
    Quantity = db.Column(db.Integer, nullable=False, default=1, comment='数量')
    TotalPrice = db.Column(db.Float, nullable=False, comment='总价')
    State = db.Column(db.String(20), nullable=False, default='pending', comment='订单状态(pending/paid/completed/cancelled)')
    OrderTime = db.Column(db.DateTime, default=datetime.now, comment='下单时间')
    PayTime = db.Column(db.DateTime, nullable=True, comment='支付时间')
    CompleteTime = db.Column(db.DateTime, nullable=True, comment='完成时间')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 建立与用户的关系
    user = db.relationship('User', backref=db.backref('orders', lazy='dynamic'))

    def __repr__(self):
        return f'<Order {self.OrderId}>'

    def to_dict(self):
        """转换为字典"""
        data = {
            'id': self.OrderId,
            'user_id': self.UserId,
            'type': self.Type,
            'item_id': self.ItemId,
            'quantity': self.Quantity,
            'total_price': float(self.TotalPrice),
            'state': self.State,
            'order_time': self.OrderTime.strftime('%Y-%m-%d %H:%M:%S') if self.OrderTime else None,
            'pay_time': self.PayTime.strftime('%Y-%m-%d %H:%M:%S') if self.PayTime else None,
            'complete_time': self.CompleteTime.strftime('%Y-%m-%d %H:%M:%S') if self.CompleteTime else None,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

        # 根据订单类型添加相关信息
        if self.Type == 'book':
            book = Book.query.get(self.ItemId)
            if book:
                data['item'] = {
                    'title': book.Title,
                    'cover_image': book.CoverImage
                }
        elif self.Type == 'food':
            food = Food.query.get(self.ItemId)
            if food:
                data['item'] = {
                    'name': food.FoodName,
                    'price': float(food.FoodPrice),
                    'image': food.FoodImage,
                    'type': food.FoodType
                }

        # 添加用户信息
        if self.user:
            data['user'] = {
                'username': self.user.UserName,
                'email': self.user.UserEmail
            }

        return data

class ClubNews(db.Model):
    """社团新闻模型"""
    __tablename__ = 'clubnews'
    
    NewsId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Title = db.Column(db.String(200), nullable=False, comment='标题')
    CoverImage = db.Column(db.String(200), nullable=True, comment='宣传图URL')
    FoundingTime = db.Column(db.DateTime, nullable=True, comment='创社时间')
    Introduction = db.Column(db.Text, nullable=True, comment='社团介绍')
    ClubBrief = db.Column(db.String(500), nullable=True, comment='社团简介')
    LeaderPhoto = db.Column(db.String(200), nullable=True, comment='部长写实照URL')
    MemberCount = db.Column(db.Integer, default=0, comment='成员数')
    ActivityTime = db.Column(db.String(100), nullable=True, comment='活动时间')
    ActivityLocation = db.Column(db.String(200), nullable=True, comment='活动地点')
    ClubRules = db.Column(db.Text, nullable=True, comment='社团规则')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def __repr__(self):
        return f'<ClubNews {self.Title}>'
    
    def to_list_dict(self):
        """转换为列表展示的字典"""
        return {
            'id': self.NewsId,
            'title': self.Title,
            'cover_image': self.CoverImage,
            'founding_time': self.FoundingTime.strftime('%Y-%m-%d %H:%M:%S') if self.FoundingTime else None,
            'introduction': self.Introduction,
            'club_brief': self.ClubBrief,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None
        }
    
    def to_dict(self):
        """转换为详情字典"""
        return {
            'id': self.NewsId,
            'title': self.Title,
            'cover_image': self.CoverImage,
            'leader_photo': self.LeaderPhoto,
            'founding_time': self.FoundingTime.strftime('%Y-%m-%d %H:%M:%S') if self.FoundingTime else None,
            'member_count': self.MemberCount,
            'activity_time': self.ActivityTime,
            'activity_location': self.ActivityLocation,
            'introduction': self.Introduction,
            'club_brief': self.ClubBrief,
            'club_rules': self.ClubRules,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class CampusActivity(db.Model):
    """校园动态模型"""
    __tablename__ = 'campusactivity'
    
    ActivityId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Title = db.Column(db.String(200), nullable=False, comment='标题')
    Content = db.Column(db.Text, nullable=False, comment='动态内容')
    Image1 = db.Column(db.String(200), nullable=True, comment='配图1 URL')
    Image2 = db.Column(db.String(200), nullable=True, comment='配图2 URL')
    LikeCount = db.Column(db.Integer, default=0, comment='点赞数')
    CommentCount = db.Column(db.Integer, default=0, comment='评论数')
    FavoriteCount = db.Column(db.Integer, default=0, comment='收藏数')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 建立与用户的关系
    user = db.relationship('User', backref=db.backref('activities', lazy='dynamic'))
    # 建立与评论的关系
    comments = db.relationship('ActivityComment', backref='activity', lazy='dynamic')
    
    def __repr__(self):
        return f'<CampusActivity {self.Title}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.ActivityId,
            'user_id': self.UserId,
            'user_avatar': self.user.profile.Avatar if self.user and self.user.profile else None,
            'user_nickname': self.user.profile.Nickname if self.user and self.user.profile else self.user.UserName if self.user else None,
            'title': self.Title,
            'content': self.Content,
            'image1': self.Image1,
            'image2': self.Image2,
            'like_count': self.LikeCount,
            'comment_count': self.CommentCount,
            'favorite_count': self.FavoriteCount,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class ActivityComment(db.Model):
    """校园动态评论模型"""
    __tablename__ = 'activitycomment'
    
    CommentId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    ActivityId = db.Column(db.Integer, db.ForeignKey('campusactivity.ActivityId'), nullable=False)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    Content = db.Column(db.Text, nullable=False, comment='评论内容')
    LikeCount = db.Column(db.Integer, default=0, comment='点赞数')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='评论时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 建立与用户的关系
    user = db.relationship('User', backref=db.backref('activity_comments', lazy='dynamic'))
    
    def __repr__(self):
        return f'<ActivityComment {self.CommentId}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.CommentId,
            'activity_id': self.ActivityId,
            'user_id': self.UserId,
            'user_avatar': self.user.profile.Avatar if self.user and self.user.profile else None,
            'user_nickname': self.user.profile.Nickname if self.user and self.user.profile else self.user.UserName if self.user else None,
            'content': self.Content,
            'like_count': self.LikeCount,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }

class RadarChart(db.Model):
    """分维雷达图模型（学生课程成绩）"""
    __tablename__ = 'radarchart'
    
    ChartId = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserId = db.Column(db.Integer, db.ForeignKey('user.UserId'), nullable=False)
    CourseScores = db.Column(db.JSON, nullable=False, comment='课程分数JSON')
    CreateTime = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    UpdateTime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 建立与用户的关系
    user = db.relationship('User', backref=db.backref('radar_charts', lazy='dynamic'))
    
    def __repr__(self):
        return f'<RadarChart {self.ChartId}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.ChartId,
            'user_id': self.UserId,
            'course_scores': self.CourseScores,
            'create_time': self.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if self.CreateTime else None,
            'update_time': self.UpdateTime.strftime('%Y-%m-%d %H:%M:%S') if self.UpdateTime else None
        }